using Devil;
using GameToolkit.BehaviourTree;
using LitJson;
using System.Text;
using UnityEditor;
using UnityEditor.AssetImporters;
using UnityEditor.Callbacks;
using UnityEngine;

namespace GameToolkit.Editor
{
    [ScriptedImporter(1, "behaviourtree")]
    public class BehaviourTreeImporter : JsonAssetImpoter<BehaviourTreeAsset>
    {
        [MenuItem("CONTEXT/BehaviourTreeAsset/Save As")]
        static void ExportAsset(MenuCommand cmd)
        {
            var ai = cmd.context as BehaviourTreeAsset;
            if(ai != null)
            {
                var file = EditorUtility.SaveFilePanelInProject("Save BehaviourTree As", $"{ai.name}_copy", "behaviourtree", "Save behaviuor tree asset.");
                if (string.IsNullOrEmpty(file))
                    return;
                var json = JsonSerializedObject.ExportFrom(ai);
                if (json == null)
                    return;
                NativeFileSystem.WriteAllText(file, JsonMapper.ToJson(json), Encoding.UTF8);
                AssetDatabase.ImportAsset(file);
            }
        }

        [MenuItem("CONTEXT/BehaviourTreeAsset/Open With New Editor")]
        static void OpenAsset(MenuCommand cmd)
        {
            var ai = cmd.context as BehaviourTreeAsset;
            if (ai != null)
                BehaviourTreeEditor.OpenAsset(ai, true);
        }

        [OnOpenAsset(OnOpenAssetAttributeMode.Execute)]
        static bool OpenAsset(int instanceID, int line)
        {
            var inst = EditorUtility.InstanceIDToObject(instanceID) as BehaviourTreeAsset;
            if (inst == null)
                return false;
            BehaviourTreeEditor.OpenAsset(inst, false);
            return true;
        }

    }
}
